구조체 활용

✒️ 2025-05-15 15:48 내용 수정

수제비 2024 정보처리기사 필기 5판 1권의 내용을 정리
TCPSchool의 내용을 정리


1. 구조체 배열 선언

#include <stdio.h>
#include <string.h>

struct book
{
	// 멤버 변수
	char title[50];
	char author[50];
	int price;
};

int main(void)
{
    struct book best_seller[3] = {
        {"세이노의 가르침", "세이노", 12800},
        {"원씽", "게리 켈러, 제이 파파산", 16000},
        {"역행자", "자청", 17500}
    };
    int arr_size = sizeof(best_seller) / sizeof(best_seller[0]);

    for(int i = 0; i < arr_size; i++) {
        printf("%s | %s | %d\n", best_seller[i].title, 
	        best_seller[i].author, best_seller[i].price);
    }
    return 0;
}
세이노의 가르침 | 세이노 | 12800     
원씽 | 게리 켈러, 제이 파파산 | 16000
역행자 | 자청 | 17500

2. 구조체를 가리키는 포인터

// 포인터 선언
struct 구조체이름* 구조체포인터명;

// 포인터로 구조체 멤버 접근
(*구조체포인터).멤버변수명;
구조체포인터->멤버변수명;
// 배열의 경우
int arr[3] = {1, 2, 3};
int *p = arr;   // 배열 이름 = 주소

// 구조체의 경우
struct Student {
    int id;
    char name[20];
};

struct Student s = {1, "Alice"}; // s는 구조체 전체
// struct Student *ps = s;   // 컴파일 오류
struct Student *ps = &s;
struct book best_seller = {"title", "author", 10000};
struct book* pb = &best_seller;

(*pb).title;
pb->title;

3. 함수와 구조체

#include <stdio.h>

typedef struct {
    char title[30];
    int stock;
    int price;
} BOOK;

int total(BOOK b)
{
    return b.stock * b.price;
}

int main(void)
{
    BOOK textbook = {"C 입문", 15, 16000};
    printf("%s의 총 개수는 %d권이고, 전체 가격은 %d이다.", 
	    textbook.title, textbook.stock, total(textbook));
    return 0;
}
C 입문의 총 개수는 15권이고, 전체 가격은 240000이다.

4. 중첩된 구조체

struct 구조체1이름
{
	타입 구조체1멤버1;
	타입 구조체1멤버2;
}

struct 구조체2이름
{
	타입 구조체2멤버1;
	타입 구조체2멤버2;
	구조체1이름 구조체1멤버변수명;
	...
}
#include <stdio.h>

typedef struct { // 멤버로 쓸 구조체
    char name[30];
    char location[50];
} Publisher;

typedef struct { // 상위 구조체
    char title[50];
    int price;
    Publisher pubInfo;  // 중첩 구조체로 설정
} Book;

int main(void) {
    Book b1 = {
        "C 언어 완전 정복",
        22000,
        {"한빛미디어", "서울시 마포구"}
    };

    printf("제목: %s\n", b1.title);
    printf("가격: %d원\n", b1.price);
    printf("출판사: %s\n", b1.pubInfo.name);
    printf("위치: %s\n", b1.pubInfo.location);

    return 0;
}
제목: C 언어 완전 정복
가격: 22000원
출판사: 한빛미디어
위치: 서울시 마포구